<?php
App::import('Model', 'Property');
App::import('Model', 'Person');
App::import('Model', 'RefinancingPlan');

class PeopleController extends AppController {
    var $name = 'People';

    function index() {
        $this->Person->recursive = 0;
        $this->set('people', $this->paginate());
    }

    function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid person', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('person', $this->Person->read(null, $id));
    }

    function add() {    	
        if (!empty($this->data)) {
            $this->Person->create();           
            if ($this->Person->save($this->data)) {            	
                $this->Session->setFlash(__('The person has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The person could not be saved. Please, try again.', true));
            }
        }
        $addresses = $this->Person->Address->find('list');
        $idCardTypes = $this->Person->IdCardType->find('list',
                array('conditions' => array('IdCardType.lookup_type' => 'ID_CARD_TYPE')));
        $this->set(compact('addresses', 'idCardTypes'));
    }

    function edit($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid person', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->Person->save($this->data)) {
                $this->Session->setFlash(__('The person has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The person could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Person->read(null, $id);
        }
        $addresses = $this->Person->Address->find('list');
        $idCardTypes = $this->Person->IdCardType->find('list',
                array('conditions' => array('IdCardType.lookup_type' => 'ID_CARD_TYPE')));
        $this->set(compact('addresses', 'idCardTypes'));
    }

    function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for person', true));
            $this->redirect(array('action'=>'index'));
        }
        if ($this->Person->delete($id)) {
            $this->Session->setFlash(__('Person deleted', true));
            $this->redirect(array('action'=>'index'));
        }
        $this->Session->setFlash(__('Person was not deleted', true));
        $this->redirect(array('action' => 'index'));
    }
    
    /**
     * Muestra todas las personas que pueden acordar un plan de pago.
     * o cuando seleccione acordar un plan de pago para un deudor,
     * avisarle en ese momento que no es posible.
     * en el refinance(person_id). 
     */
    function refinance_index()
    {	
	    $pers = new Person;
	    $prop = new Property;
	    $info  = $prop->find('all'); 
	    $ownersCond=array();

	  foreach ($info as $unaPropiedad) {
     	//var_dump( $unaPropiedad["Property"]["owner_id"]) ;
      	$miPersona = $pers->find('first',array('conditions' => 
      	array('OR' => array( 
      						array('Person.person_id' => $unaPropiedad["Property"]["owner_id"]),
      						array('Person.person_id' => $unaPropiedad["Property"]["tenant_id"])
      						)
			 )
			 ));
     	//var_dump($miPersona["Person"]["surname"]);
		array_push($ownersCond, $miPersona["Person"]["person_id"]);
	  }

	  $conditions=array('Person.person_id' => $ownersCond) ;
	  $this->set('people',$this->paginate($conditions));//si quiero que muestre TODAS las personas$this->set('people',$this->paginate());
    }    
    
    /**
     * Acuerdo de plan de pago con una persona. 
     * Misma observacion que en refinance_all.
     * @param $id id de la persona con la cual se acordara un plan de pago.
     */
    function refinance_index_person($id = null)
    {
    	if (!$id) {
            $this->Session->setFlash(__('Invalid person', true));
            $this->redirect(array('action' => 'refinance_debtors'));
        }      
        
        // Mostrar los edificios de esa persona.
        $sql = "select distinct b.building_id, b.building_name,p.person_id
        		from people p 
        		inner join properties prop on owner_id = p.person_id or tenant_id = p.person_id 
        		or owner_representative_id = p.person_id or tenant_representative_id = p.person_id  
        		inner join buildings b on b.building_id = prop.building_id 
        		where p.person_id = $id;";
        
        $toRefinance  = $this->Person->query($sql);        
        $this->set('toRefinance',$toRefinance);        
        
        // para cada tipo de propiedades (de la que es dueño, inquilino, etc)
        // deberia filtrar por aquellas en las cuales las expensas estan impagas.
    }    
    
    /**
     * 
     * Refinancia las propiedades.
     * Ya contiene los datos de la persona, y el edificio.
     * @param $data
     */
    function refinance_index_properties()
    {       	    	
   		if (empty($this->data))
   		{		
   			$person_id = $this->params['url']['person_id'];
    		$building_id = $this->params['url']['building_id'];
   			
			$owned_properties = $this->Person->PropertyOwner->find('all',
					array('conditions' => array('PropertyOwner.owner_id' => $person_id ,
												'PropertyOwner.building_id' =>$building_id)));	
					
			foreach($owned_properties as $key => $owned_property)
			{			
				$owned_properties[$key]['PropertyOwner']['refinanced'] = false;				
			}
			
			$tenant_properties = $this->Person->PropertyTenant->find('all',
					array('conditions' => array('PropertyTenant.tenant_id' => $person_id ,
												'PropertyTenant.building_id' =>$building_id)));
					
//			var_dump($tenant_properties);
//			die();		

   			foreach($tenant_properties as $key => $tenant_property)
			{			
				$tenant_properties[$key]['PropertyTenant']['refinanced'] = false;				
			}
			
			// Setear los tipos de expensas.
			$expenditureTypes =  new ExpenditureType;
			$expenses_types = $expenditureTypes->ExpenditureTypeSource->find('list',
                array('conditions' => array('ExpenditureTypeSource.lookup_type' => 'EXPENDITURE_TYPE_SOURCE')));			

			$this->set(compact('person_id','building_id','owned_properties','tenant_properties','expenses_types'));
   		}
   		else 
   		{	
   			$data_refinancing['building_id'] = $this->data['building_id'];
   			$data_refinancing['person_id'] = $this->data['person_id'];
   			$data_refinancing['expenditure_type_source'] = $this->data['expenditure_type'];
   			$data_refinancing['installment_quantity'] = $this->data['installment_quantity'];
   			
   			if ($data_refinancing['installment_quantity']==0) 
   			{
            	$this->Session->setFlash(__('Installment quantity must be greater than zero', true));
   			}
   			else 
   			{
	   			$j = 0;
	   			for($i = 1;$i<= count($this->data)-4;$i++)
	   			{   				
	   				
	  				if (!empty($this->data[$i]['PropertyOwner'])&&(array_key_exists('refinanced',$this->data[$i]['PropertyOwner'])))
	  				{
	  					$data_refinancing['properties'][$j] =  $this->data[$i]['PropertyOwner']['property_id'];
	  					$j++;
	  				}
	   				if (!empty($this->data[$i]['PropertyTenant'])&&(array_key_exists('refinanced',$this->data[$i]['PropertyTenant'])))
	  				{
	  					$data_refinancing['properties'][$j] =  $this->data[$i]['PropertyTenant']['property_id'];
	  					$j++;
	  				}
	   			}   			

	   			$refinancingPlan = new RefinancingPlan;
	   			$refinancingPlan->create_plan($data_refinancing);
	   			
	            $this->redirect(array('controller' => 'RefinancingPlans','action' => 'index'));
   			}
   		}
    }
}
?>
